import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import type { User } from '@/types'

/**
 * VIP状态信息接口
 */
interface VipStatus {
  userType: string
  isVip: boolean
  vipExpireTime?: string
  daysLeft?: number
  storageQuota: number
  storageUsed: number
  storageUsagePercentage: number
}

/**
 * 功能使用统计接口
 */
interface FeatureUsage {
  featureCode: string
  featureName: string
  used: number
  limit: number
  limitPeriod: string
  percentage: number
  status: 'success' | 'warning' | 'exception'
}

/**
 * 支付订单接口
 */
interface PaymentOrder {
  id: number
  orderNo: string
  planType: string
  amount: number
  status: string
  paymentMethod: string
  createdAt: string
  paidAt?: string
  expiresAt?: string
  remark?: string
}

/**
 * VIP订阅信息接口
 */
interface VipSubscription {
  id: number
  userId: number
  orderId?: number
  planType: string
  planName: string
  startDate: string
  endDate: string
  status: string
  statusDescription: string
  autoRenew: boolean
  originalAmount?: number
  discountAmount?: number
  actualAmount?: number
  createdAt: string
  daysLeft?: number
}

/**
 * VIP套餐信息
 */
export const VIP_PLANS = {
  MONTHLY_VIP: {
    name: '月度VIP',
    price: 29.90,
    originalPrice: 29.90,
    period: '月',
    features: [
      '100GB 存储空间',
      '无限团队创建',
      'AI工作报告无限制',
      '优先客服支持'
    ],
    popular: false
  },
  YEARLY_VIP: {
    name: '年度VIP',
    price: 299.00,
    originalPrice: 358.80,
    period: '年',
    features: [
      '100GB 存储空间',
      '无限团队创建',
      'AI工作报告无限制',
      '优先客服支持'
    ],
    popular: true,
    discount: '节省 ¥59.80'
  }
} as const

/**
 * VIP状态管理Store
 */
export const useVipStore = defineStore('vip', () => {
  // 状态
  const vipStatus = ref<VipStatus | null>(null)
  const featureUsages = ref<FeatureUsage[]>([])
  const paymentOrders = ref<PaymentOrder[]>([])
  const subscriptions = ref<VipSubscription[]>([])
  const loading = ref(false)
  const upgradeDialogVisible = ref(false)

  // 分页状态
  const paymentOrdersPagination = ref({
    page: 0,
    size: 10,
    total: 0,
    totalPages: 0
  })

  // 计算属性
  const isVip = computed(() => vipStatus.value?.isVip || false)
  const userType = computed(() => vipStatus.value?.userType || 'BASIC')
  const daysLeft = computed(() => vipStatus.value?.daysLeft || 0)
  const storageUsagePercentage = computed(() => vipStatus.value?.storageUsagePercentage || 0)

  // 存储使用状态
  const storageStatus = computed(() => {
    const percentage = storageUsagePercentage.value
    if (percentage >= 90) return 'exception'
    if (percentage >= 70) return 'warning'
    return 'success'
  })

  // VIP即将过期警告
  const isExpiringSoon = computed(() => {
    return isVip.value && daysLeft.value > 0 && daysLeft.value <= 7
  })

  // 获取当前活跃订阅
  const currentSubscription = computed(() => {
    return subscriptions.value.find(sub => sub.status === 'ACTIVE') || null
  })

  // 方法
  const fetchVipStatus = async () => {
    loading.value = true
    try {
      const response = await fetch('/api/vip/status', {
        headers: {
          'Authorization': `Bearer ${localStorage.getItem('token')}`
        }
      })
      const result = await response.json()
      if (result.code === 200 || result.success) {
        vipStatus.value = result.data
      }
    } catch (error) {
      console.error('获取VIP状态失败:', error)
    } finally {
      loading.value = false
    }
  }

  const fetchFeatureUsages = async () => {
    try {
      const response = await fetch('/api/vip/feature-usages', {
        headers: {
          'Authorization': `Bearer ${localStorage.getItem('token')}`
        }
      })
      const result = await response.json()
      if (result.code === 200 || result.success) {
        featureUsages.value = result.data
        
        // 增强：从前端现有数据更新团队创建和AI报告统计
        await enhanceFeatureUsagesWithFrontendData()
      }
    } catch (error) {
      console.error('获取功能使用统计失败:', error)
      
      // 如果后端API失败，尝试从前端数据构建基础统计
      await buildFeatureUsagesFromFrontendData()
    }
  }

  const fetchPaymentOrders = async (page = 0, size = 10, sortBy = 'createdAt', sortDirection = 'desc') => {
    try {
      const response = await fetch(`/api/vip/orders?page=${page}&size=${size}&sortBy=${sortBy}&sortDirection=${sortDirection}`, {
        headers: {
          'Authorization': `Bearer ${localStorage.getItem('token')}`
        }
      })
      const result = await response.json()
      if (result.code === 200 || result.success) {
        // 处理分页响应
        const pageData = result.data
        paymentOrders.value = pageData?.content || []
        
        // 更新分页信息
        paymentOrdersPagination.value = {
          page: pageData?.number || 0,
          size: pageData?.size || 10,
          total: pageData?.totalElements || 0,
          totalPages: pageData?.totalPages || 0
        }
      }
    } catch (error) {
      console.error('获取支付订单失败:', error)
    }
  }

  const fetchSubscriptions = async () => {
    try {
      const response = await fetch('/api/vip/subscriptions', {
        headers: {
          'Authorization': `Bearer ${localStorage.getItem('token')}`
        }
      })
      const result = await response.json()
      if (result.code === 200 || result.success) {
        subscriptions.value = result.data
      }
    } catch (error) {
      console.error('获取订阅列表失败:', error)
    }
  }

  const createPaymentOrder = async (planType: string) => {
    try {
      const response = await fetch('/api/vip/orders', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${localStorage.getItem('token')}`
        },
        body: JSON.stringify({ planType })
      })
      
      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`)
      }
      
      const result = await response.json()
      console.log('创建订单响应:', result) // 添加调试日志
      
      // 根据后端实际返回的结构判断成功
      if (result.code === 200 || result.success) {
        return result.data
      } else {
        throw new Error(result.message || '创建订单失败')
      }
    } catch (error) {
      console.error('创建支付订单失败:', error)
      throw error
    }
  }

  const createAlipayPayment = async (orderNo: string) => {
    try {
      const response = await fetch(`/api/payment/alipay/create/${orderNo}`, {
        method: 'POST',
        headers: {
          'Authorization': `Bearer ${localStorage.getItem('token')}`
        }
      })
      
      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`)
      }
      
      const result = await response.json()
      console.log('创建支付响应:', result) // 添加调试日志
      
      // 修复: 正确处理AlipayService返回的模拟支付HTML
      if (result.code === 200 || result.success) {
        // 支付宝返回的HTML在 data 字段中
        return result.data || result.message
      } else {
        throw new Error(result.message || '创建支付失败')
      }
    } catch (error) {
      console.error('创建支付宝支付失败:', error)
      throw error
    }
  }

  const checkFeaturePermission = async (featureCode: string) => {
    try {
      const response = await fetch(`/api/vip/check-feature/${featureCode}`, {
        headers: {
          'Authorization': `Bearer ${localStorage.getItem('token')}`
        }
      })
      const result = await response.json()
      return (result.code === 200 || result.success) ? result.data : false
    } catch (error) {
      console.error('检查功能权限失败:', error)
      return false
    }
  }

  const getRemainingUsage = async (featureCode: string) => {
    try {
      const response = await fetch(`/api/vip/remaining-usage/${featureCode}`, {
        headers: {
          'Authorization': `Bearer ${localStorage.getItem('token')}`
        }
      })
      const result = await response.json()
      return (result.code === 200 || result.success) ? result.data : 0
    } catch (error) {
      console.error('获取剩余使用量失败:', error)
      return 0
    }
  }

  const cancelSubscription = async (subscriptionId: number) => {
    try {
      const response = await fetch(`/api/vip/subscriptions/${subscriptionId}/cancel`, {
        method: 'POST',
        headers: {
          'Authorization': `Bearer ${localStorage.getItem('token')}`
        }
      })
      const result = await response.json()
      if (result.code === 200 || result.success) {
        await Promise.all([
          fetchVipStatus(),
          fetchSubscriptions()
        ])
      } else {
        throw new Error(result.message || '取消订阅失败')
      }
    } catch (error) {
      console.error('取消订阅失败:', error)
      throw error
    }
  }

  const showUpgradeDialog = () => {
    upgradeDialogVisible.value = true
  }

  const hideUpgradeDialog = () => {
    upgradeDialogVisible.value = false
  }

  // 初始化方法
  const init = async () => {
    await Promise.all([
      fetchVipStatus(),
      fetchFeatureUsages(),
      fetchPaymentOrders(),
      fetchSubscriptions()
    ])
  }

  // 格式化文件大小
  const formatFileSize = (bytes: number | string): string => {
    const numBytes = typeof bytes === 'string' ? parseInt(bytes, 10) : bytes
    if (!numBytes || numBytes === 0) return '0 B'
    const k = 1024
    const sizes = ['B', 'KB', 'MB', 'GB', 'TB']
    const i = Math.floor(Math.log(numBytes) / Math.log(k))
    return parseFloat((numBytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
  }

  // 格式化日期
  const formatDate = (dateString: string): string => {
    if (!dateString) return ''
    return new Date(dateString).toLocaleDateString('zh-CN', {
      year: 'numeric',
      month: 'long',
      day: 'numeric'
    })
  }

  // 格式化剩余天数
  const formatDaysLeft = (days: number): string => {
    if (days <= 0) return '已过期'
    if (days === 1) return '明天过期'
    if (days <= 7) return `${days}天后过期`
    if (days <= 30) return `${days}天后过期`
    return `${Math.floor(days / 30)}个月后过期`
  }

  // 从前端现有数据增强功能使用统计
  const enhanceFeatureUsagesWithFrontendData = async () => {
    try {
      // 动态导入store以避免循环依赖
      const { useWorkReportStore } = await import('@/stores/workReportStore')
      const { teamApi } = await import('@/api/team')
      
      const workReportStore = useWorkReportStore()
      
      // 获取前端数据
      await Promise.all([
        workReportStore.fetchReportStats(),
        // 使用新的API获取用户创建的团队数量
      ])
      
      // 获取用户创建的团队数量（而不是参与的团队数量）
      const teamCountResponse = await teamApi.getMyCreatedTeamCount()
      const createdTeamCount = teamCountResponse.data || 0
      
      // 更新团队创建统计
      const teamUsageIndex = featureUsages.value.findIndex(usage => usage.featureCode === 'TEAM_CREATE')
      if (teamUsageIndex !== -1) {
        featureUsages.value[teamUsageIndex].used = createdTeamCount
      }
      
      // 更新AI报告统计
      const reportUsageIndex = featureUsages.value.findIndex(usage => usage.featureCode === 'AI_REPORT')
      if (reportUsageIndex !== -1 && workReportStore.reportStats) {
        featureUsages.value[reportUsageIndex].used = workReportStore.reportStats.totalReports
      }
      
    } catch (error) {
      console.warn('从前端数据增强功能统计失败:', error)
    }
  }

  // 从前端数据构建基础功能使用统计
  const buildFeatureUsagesFromFrontendData = async () => {
    try {
      // 动态导入store以避免循环依赖
      const { useWorkReportStore } = await import('@/stores/workReportStore')
      const { teamApi } = await import('@/api/team')
      
      const workReportStore = useWorkReportStore()
      
      // 获取前端数据
      await Promise.all([
        workReportStore.fetchReportStats(),
        // 使用新的API获取用户创建的团队数量
      ])
      
      // 获取用户创建的团队数量（而不是参与的团队数量）
      const teamCountResponse = await teamApi.getMyCreatedTeamCount()
      const createdTeamCount = teamCountResponse.data || 0
      
      // 构建基础功能使用统计
      const basicUsages: FeatureUsage[] = [
        {
          featureCode: 'TEAM_CREATE',
          featureName: '团队创建',
          used: createdTeamCount,
          limit: isVip.value ? -1 : 3,
          limitPeriod: '总计',
          percentage: isVip.value ? 0 : (createdTeamCount / 3) * 100,
          status: isVip.value ? 'success' : (createdTeamCount >= 3 ? 'exception' : 'success')
        },
        {
          featureCode: 'AI_REPORT',
          featureName: 'AI工作报告',
          used: workReportStore.reportStats?.totalReports || 0,
          limit: isVip.value ? -1 : 30,
          limitPeriod: '月度',
          percentage: isVip.value ? 0 : ((workReportStore.reportStats?.totalReports || 0) / 30) * 100,
          status: isVip.value ? 'success' : ((workReportStore.reportStats?.totalReports || 0) >= 27 ? 'exception' : 'success')
        }
      ]
      
      featureUsages.value = basicUsages
      
    } catch (error) {
      console.warn('从前端数据构建功能统计失败:', error)
      // 设置默认空数组
      featureUsages.value = []
    }
  }

  return {
    // 状态
    vipStatus,
    featureUsages,
    paymentOrders,
    subscriptions,
    loading,
    upgradeDialogVisible,
    paymentOrdersPagination,

    // 计算属性
    isVip,
    userType,
    daysLeft,
    storageUsagePercentage,
    storageStatus,
    isExpiringSoon,
    currentSubscription,

    // 方法
    fetchVipStatus,
    fetchFeatureUsages,
    fetchPaymentOrders,
    fetchSubscriptions,
    createPaymentOrder,
    createAlipayPayment,
    checkFeaturePermission,
    getRemainingUsage,
    cancelSubscription,
    showUpgradeDialog,
    hideUpgradeDialog,
    init,

    // 工具方法
    formatFileSize,
    formatDate,
    formatDaysLeft,
    
    // 新增：前端数据增强方法
    enhanceFeatureUsagesWithFrontendData,
    buildFeatureUsagesFromFrontendData
  }
})

export type { VipStatus, FeatureUsage, PaymentOrder, VipSubscription }